﻿using BLL;
using LibraryMIS2019.Properties;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LibraryMIS2019
{
    public partial class LibraryUI : Form
    {
        private string operation = "I";     //图书操作类型变量，当为I时是新增书籍，当为U时是更新书籍信息
        BusinessLogic logic = new BusinessLogic();  //新建业务逻辑类对象logic
        DataSet ds; //定义数据集对象

        bool State = false;//还书管理模块状态阀值，True：还书；False：查询

        public LibraryUI()
        {
            InitializeComponent();
            //控件透明化处理
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            labUserName.BackColor = Color.FromArgb(0, 255, 255, 255);//UI窗口下方Label字体透明化处理
            labLoginUser.BackColor = Color.FromArgb(0, 255, 255, 255);//UI窗口下方Label字体透明化处理

            tag3lablErrorString.Hide();//隐藏还书管理警告提示
        }

        #region 标签颜色渲染处理
        /// <summary>
        /// 修改TabPage标签的颜色
        /// 1.将TabControl控件DrawMode属性修改为：OwnerDrawFixed
        /// 2.通过编辑TabControl控件的DrawItem事件进行本事件的编程实现
        /// </summary>
        private void tabControlLib_DrawItem(object sender, DrawItemEventArgs e)
        {
            //获取TabControl主控件的工作区域
            Rectangle rec = tabControlLib.ClientRectangle;
            //获取背景图片，我的背景图片在项目资源文件中。
            Image backImage = Resources.background;

            //新建一个StringFormat对象，用于对标签文字的布局设置
            StringFormat StrFormat = new StringFormat();
            StrFormat.LineAlignment = StringAlignment.Center;// 设置文字垂直方向居中
            StrFormat.Alignment = StringAlignment.Center;// 设置文字水平方向居中           

            // 标签背景填充颜色：#EEFFFF(238, 255, 255)，#FFFFEE(255, 255, 238)
            //当然也可以设置不同颜色值
            //SolidBrush blue1 = new SolidBrush(Color.FromArgb(238, 255, 255));
            SolidBrush color1 = new SolidBrush(Color.FromArgb(238, 255, 255));
            SolidBrush color2 = new SolidBrush(Color.FromArgb(255, 255, 238));
            SolidBrush color3 = new SolidBrush(Color.FromArgb(238, 255, 255));
            SolidBrush color4 = new SolidBrush(Color.FromArgb(255, 255, 238));
            SolidBrush color5 = new SolidBrush(Color.FromArgb(238, 255, 255));
            SolidBrush color6 = new SolidBrush(Color.FromArgb(255, 255, 238));
            SolidBrush color7 = new SolidBrush(Color.FromArgb(238, 255, 255));
            SolidBrush bruFont = new SolidBrush(Color.FromArgb(0, 34, 85));// 标签字体颜色
            Font fontStyle = new System.Drawing.Font("微软雅黑", 10F);//设置标签字体样式 
            //绘制主控件的背景
            e.Graphics.DrawImage(backImage, 0, 0, tabControlLib.Width, tabControlLib.Height);
            //绘制背景色
            Rectangle rec1 = tabControlLib.GetTabRect(0);
            e.Graphics.FillRectangle(color1, rec1);
            Rectangle rec2 = tabControlLib.GetTabRect(1);
            e.Graphics.FillRectangle(color2, rec2);
            Rectangle rec3 = tabControlLib.GetTabRect(2);
            e.Graphics.FillRectangle(color3, rec3);
            Rectangle rec4 = tabControlLib.GetTabRect(3);
            e.Graphics.FillRectangle(color4, rec4);
            Rectangle rec5 = tabControlLib.GetTabRect(4);
            e.Graphics.FillRectangle(color5, rec5);
            Rectangle rec6 = tabControlLib.GetTabRect(5);
            e.Graphics.FillRectangle(color6, rec6);
            Rectangle rec7 = tabControlLib.GetTabRect(6);
            e.Graphics.FillRectangle(color7, rec7);
            //绘制标签样式
            for (int i = 0; i < tabControlLib.TabPages.Count; i++)
            {
                //获取标签头的工作区域
                Rectangle recChild = tabControlLib.GetTabRect(i);
                //绘制标签头背景颜色
                // e.Graphics.FillRectangle(blue1, recChild);
                //绘制标签头的文字                        
                e.Graphics.DrawString(tabControlLib.TabPages[i].Text, fontStyle, bruFont, recChild, StrFormat);
            }
        }
        #endregion
        #region 图书类别下拉实现
        /// <summary>
        /// 下拉菜单方法实现
        /// </summary>
        private void DropDownBookClass(ComboBox controlName)
        {
            DataSet bookClass = logic.GetBookClass();
            //数据源绑定到控件
            controlName.DataSource = bookClass.Tables[0];
            controlName.DisplayMember = "classname";
            controlName.ValueMember = "classid";
        }
        private void tag1cbBookCategory1_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownBookClass(tag1cbBookCategory1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统信息");
            }
        }

        private void tag1cbBookCategory2_VisibleChanged(object sender, EventArgs e)
        {
            try
            {
                DropDownBookClass(tag1cbBookCategory2);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统信息");
            }
        }
        #endregion
        #region 图书信息处理
        /// <summary>
        /// 书籍入库数据校验
        /// </summary>
        private string BookInfoDataValidation()
        {
            if (tag1txtBookID.Text == "") { tag1txtBookID.Focus(); return "索书号不能为空值！"; }
            if (tag1txtBookName1.Text == "") { tag1txtBookName1.Focus(); return "书名不能为空值！"; }
            if (tag1txtISBN.Text == "") { tag1txtISBN.Focus(); return "图书标准编号不能为空值！"; }
            if (tag1txtAuthor.Text == "") { tag1txtAuthor.Focus(); return "作者不能为空值！"; }
            if (tag1txtPublisher.Text == "") { tag1txtPublisher.Focus(); return "出版社不能为空值！"; }
            return "";
        }
        private BookClass FindBookClassByBookClassID(string bookClassID)
        {
            return logic.FindBookClass(bookClassID);
        }
        private void tag1btnEditBook_Click(object sender, EventArgs e)
        {
            string errorString = BookInfoDataValidation();
            if (errorString.Length > 0) { MessageBox.Show(errorString, "系统提示"); return; }
            //获取控件值
            BookInfo bo = new BookInfo();
            bo.BookID = tag1txtBookID.Text.Trim();
            bo.BookName = tag1txtBookName1.Text.Trim();
            bo.ISBN = tag1txtISBN.Text.Trim();
            bo.Author = tag1txtAuthor.Text.Trim();
            bo.Publisher = tag1txtPublisher.Text.Trim();
            if (tag1txtWordCount.Text == "")
                bo.WordCount = 0;
            else bo.WordCount = Convert.ToInt32(tag1txtWordCount.Text.Trim());
            if (tag1txtPageCount.Text == "")
                bo.WordCount = 0;
            else bo.WordCount = Convert.ToInt32(tag1txtPageCount.Text.Trim());
            //日期控件取值处理
            bo.PublishDate = tag1dtpPublishDate.Value.Date;

            if (tag1txtVersion.Text.Trim().Length > 0)
                bo.BookVersion = tag1txtVersion.Text.Trim();
            else bo.BookVersion = "";

            //获取下拉菜单控件的值
            var bookClassID = tag1cbBookCategory1.SelectedValue.ToString().Trim();
            //根据图书类别编号获取对应图书类别记录
            BookClass po = FindBookClassByBookClassID(bookClassID);
            bo.BookClass = po;

            logic = new BusinessLogic();
            object obj = logic.EditBook(bo, operation);
            if (obj != null)
            {
                if (obj.ToString() == "这是重复记录")
                    MessageBox.Show("重复数据，请勿重复插入！", "系统提示");
                else
                    MessageBox.Show("操作成功，数据已成功刷新", "系统提示");
            }
            tag1btnCancel_Click(null,null);//调用撤销单击事件进行控件清空处理
        }

        /// <summary>
        /// 选择“新书入库”单选按钮
        /// </summary>
        private void tag1rbInsertBook_CheckedChanged(object sender, EventArgs e)
        {
            operation = "I";
        }
        /// <summary>
        /// 选择“更新数据信息”单选按钮
        /// </summary>
        private void tag1rbUpdateBook_CheckedChanged(object sender, EventArgs e)
        {
            operation = "U";
        }
        /// <summary>
        /// 图书搜索功能实现
        /// </summary>
        private void tag1btnSearchBook_Click(object sender, EventArgs e)
        {
            string bookname = tag1txtBookName2.Text.Trim();//获取用户输入的书名查找关键字
            string classname = tag1cbBookCategory2.Text.Trim();
            ds = logic.GetBookByBookNameOrClassname(bookname, classname);//根据书名、类别名查询图书信息
            if (ds != null)
                tag1dgBookInfo.DataSource = ds.Tables[0];
            else
                MessageBox.Show("没有查询到结果", "系统提示");
        }
        /// <summary>
        /// 单元格单击事件
        /// </summary>
        private void tag1dgBookInfo_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            string selectedBookId = tag1dgBookInfo.Rows[e.RowIndex].Cells[0].Value.ToString();//获取被选行的索书号值
            ds = logic.GetBookByBookID(selectedBookId);
            if (ds.Tables[0].Rows.Count > 0)
            {
                tag1txtBookID.Text = ds.Tables[0].Rows[0][0].ToString();
                tag1txtISBN.Text= ds.Tables[0].Rows[0][1].ToString();
                tag1txtBookName1.Text = ds.Tables[0].Rows[0][2].ToString();
                tag1txtAuthor.Text= ds.Tables[0].Rows[0][3].ToString();
                tag1dtpPublishDate.Text = ds.Tables[0].Rows[0][4].ToString();
                tag1txtVersion.Text= ds.Tables[0].Rows[0][5].ToString();
                tag1txtWordCount.Text= ds.Tables[0].Rows[0][6].ToString();
                tag1txtPageCount.Text = ds.Tables[0].Rows[0][7].ToString();
                tag1txtPublisher.Text = ds.Tables[0].Rows[0][8].ToString();
                tag1cbBookCategory1.Text= ds.Tables[0].Rows[0][10].ToString();
            }
        }
        /// <summary>
        /// 撤销按钮
        /// </summary>
        private void tag1btnCancel_Click(object sender, EventArgs e)
        {
            ClearControl(tag1gbInputBooks);
            tag1rbInsertBook.Checked = true;
            var today = DateTime.Now;
            tag1dtpPublishDate.Value = today;
        }
        /// <summary>
        /// 删除记录
        /// </summary>
        private void tag1btnDeleteBook_Click(object sender, EventArgs e)
        {
            MessageBoxButtons systemBtn = MessageBoxButtons.OKCancel;//定义确定取消消息按钮
            DialogResult result = MessageBox.Show("你确定删除该数据吗？", "系统提示", systemBtn);//定义系统提示并将其赋值给对话框对象
            if (result == DialogResult.OK)
            {
                string bookid = tag1txtBookID.Text.Trim();//获取索书号
                if (logic.DeleteBook(bookid))
                {
                    MessageBox.Show("已成功删除该条记录！", "系统信息");
                    //刷新DataGridView数据源信息
                }
                else
                    MessageBox.Show("记录删除失败！请查证后再操作。", "系统信息");
                string bookname = tag1txtBookName2.Text.Trim();//获取用户输入的书名查找关键字
                string classname = tag1cbBookCategory2.Text.Trim();
                ds = logic.GetBookByBookNameOrClassname(bookname, classname);
                if (ds != null)
                    tag1dgBookInfo.DataSource = ds.Tables[0];
            }
            else return;
        }


        #endregion
        #region 清空控件内容
        private void ClearControl(Control controlName)
        {
            for (int index = 0; index < controlName.Controls.Count; index++)
            {
                // 如果是容器内部控件，则递归调用自己
                if (controlName.Controls[index].HasChildren)
                {
                    ClearControl(controlName.Controls[index]);
                }
                else
                {
                    switch (controlName.Controls[index].GetType().Name)
                    {
                        case "TextBox":
                            (controlName.Controls[index] as TextBox).Text = "";
                            break;
                        case "RadioButton":
                            (controlName.Controls[index] as RadioButton).Checked = false;
                            break;
                        case "CheckBox":
                            (controlName.Controls[index] as CheckBox).Checked = false;
                            break;
                        case "ComboBox":
                            (controlName.Controls[index] as ComboBox).Text = "";
                            (controlName.Controls[index] as ComboBox).SelectedIndex = -1;
                            break;
                        case "DataGridView":
                            (controlName.Controls[index] as DataGridView).DataSource = null;
                            break;
                        case "ListBox":
                            (controlName.Controls[index] as ListBox).Items.Clear();
                            break;
                        case "DateTimePicker":
                            (controlName.Controls[index] as DateTimePicker).Checked = false;
                            break;
                    }
                }
            }           
        }
        #endregion
        #region 菜单跳转
        private void 图书管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlLib.SelectedIndex = 0;
        }
        private void 借书管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlLib.SelectedIndex = 1;
        }
        private void 还书管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlLib.SelectedIndex = 2;
        }
        private void 续借管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlLib.SelectedIndex = 3;
        }
        private void 用户管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlLib.SelectedIndex = 4;
        }
        private void 信息维护ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlLib.SelectedIndex = 5;
        }
        private void 报表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlLib.SelectedIndex = 6;
        }
        private void 退出ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //this.Close(); //只是关闭当前窗口，若不是主窗体的话，是无法退出程序的，另外若有托管线程（非主线程），也无法干净地退出 

            //Application.Exit(); //强制所有消息中止，退出所有的窗体，但是若有托管线程（非主线程），也无法干净地退出

            //Application.ExitThread(); //强制中止调用线程上的所有消息，同样面临其它线程无法正确退出的问题

            Environment.Exit(0); //这是最彻底的退出方式，不管什么线程都被强制退出，把程序结束的很干净
        }
        private void 关于我们ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("柳职：2018软件技术2班荣誉出品", "关于我们", MessageBoxButtons.OK);
        }
        private void 用户手册ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("柳职：2018软件技术2班荣誉出品", "关于我们", MessageBoxButtons.OK);
            //xxx.Open(System.IO.Directory.GetCurrentDirectory() + "\\xxx\\xxx.docx");
        }
        #endregion
        #region 借书管理模块
        /// <summary>
        /// 显示读者相片
        /// </summary>
        /// <param name="userid"></param>
        private void Showtag2pbPhoto(string userid)
        {
            if (logic.GetPhotoByUserID(userid) != null)
                tag2pbPhoto.Image = Image.FromStream(logic.GetPhotoByUserID(userid));
        }
        private void tag2btnOK_Click(object sender, EventArgs e)
        {
            if (tag2txtReaderCode.Text.Trim() != "")
            {
                string userid = tag2txtReaderCode.Text.Trim();
                logic = new BusinessLogic();
                DataSet userlist = logic.GetUserInfo(userid);//根据用户id获取用户信息

                //判断查询集userlist的空值情况
                if(userlist.Tables.Count==1 && userlist.Tables[0].Rows.Count == 0)
                {
                    MessageBox.Show("没有此读者信息，请查证后在次操作！", "系统提示");
                    tag2txtReaderCode.Clear();
                    tag2txtReaderCode.Focus();
                }
                else
                {
                    tag2txtReaderName.Text = userlist.Tables[0].Rows[0][2].ToString();
                    tag2txtClassName.Text= userlist.Tables[0].Rows[0][10].ToString();
                    string gender= userlist.Tables[0].Rows[0][3].ToString();
                    if (gender == "True")
                        tag2rbMale.Checked = true;
                    else
                        tag2rbFemale.Checked = true;
                    Showtag2pbPhoto(userid);
                    //读取用户的借阅信息
                    ds = logic.GetBorrowBookByUserID(userid);
                    //判断返回数据集，如果数据集计数为0：没有待归还图书，否则，将数据集绑定到DataGridView控件数据源
                    if (ds.Tables[0].Rows.Count != 0)
                        tag2dgBorrowBook.DataSource = ds.Tables[0];
                    else
                    {
                        MessageBox.Show("该读者没有待归还的书籍！", "系统提示");
                    }
                }
            }
            else
            {
                MessageBox.Show("请输入读者证号！", "系统提示");
                tag2txtReaderCode.Focus();
            }
        }
        private void tag2btnBorrowBook_Click(object sender, EventArgs e)
        {
            string bookid = tag2txtBookID.Text.Trim();//获取索书号
            string userid = tag2txtReaderCode.Text.Trim();//获取读者证号
            DateTime nowTime = DateTime.Now;//获取当前时间作为借出日期

            object ob;
            logic = new BusinessLogic();

            ob = logic.InsertBorrowInfo(bookid, userid);
            if (ob.ToString() == "不可借")
                MessageBox.Show("该书已被借出，不能再借！", "系统提示");
            else if (ob.ToString() == "true")
                MessageBox.Show("借书成功！", "系统提示");
            else
                MessageBox.Show("借书失败！", "系统提示");
        }

        #endregion
        #region 还书管理模块
        private void tag3btnReturnBook_Click(object sender, EventArgs e)
        {
            string bookid = tag3txtBookID.Text.Trim();//获取用户输入索书号
            if (bookid.Length == 0)
            {
                MessageBox.Show("索书号不能为空，请进行输入！", "系统提示");
                tag3txtBookID.Focus();//将光标停至索书号输入框
                return;
            }
            if (!State) //State:False—查询查询用户借阅信息&图书信息
            {
                try
                {
                    ds = logic.GetBorrowInfo("", bookid);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        tag3txtISBN.Text = ds.Tables[0].Rows[0][7].ToString();
                        tag3txtBookName.Text= ds.Tables[0].Rows[0][8].ToString();
                        tag3txtPublisher.Text= ds.Tables[0].Rows[0][14].ToString();
                        tag3txtAuthor.Text= ds.Tables[0].Rows[0][9].ToString();
                        tag3txtUserName.Text= ds.Tables[0].Rows[0][2].ToString();
                        tag3txtClassName.Text= ds.Tables[0].Rows[0][3].ToString();

                        //男、女单选按钮被选状态实现
                        string gender= ds.Tables[0].Rows[0][4].ToString();
                        if (gender == "女")
                            tag3rbFemale.Checked = true;
                        else
                            tag3rdMale.Checked = true;

                        //是否逾期处理
                        var borrowDate = ds.Tables[0].Rows[0][5].ToString();//获取借出日期
                        DateTime BorrowDate = Convert.ToDateTime(borrowDate);//借出日期转型成日期类型

                        if ((DateTime.Now - BorrowDate).Days > 30)
                            tag3rbOverdueYes.Checked = true;//逾期
                        else
                            tag3rbOverdueNo.Checked = true;//不逾期

                        //用户借阅信息处理
                        string userid = ds.Tables[0].Rows[0][0].ToString();//获取用户读者编号
                        DataSet borrowInfoByUser = logic.GetBorrowInfo(userid, "");//根据用户编号获取借阅信息
                        if (borrowInfoByUser.Tables[0].Rows.Count > 0)
                        {
                            tag3dgBorrowInfo.AutoGenerateColumns = false;//不自动创建列，只显示自定义列
                            tag3dgBorrowInfo.DataSource = borrowInfoByUser.Tables[0];
                            tag3btnReturnBook.Text = "还 书";//将查询按钮修改为还书按钮
                            State = true;//将状态阀值修改，True：还书操作
                        }
                            
                        else
                            MessageBox.Show("该用户没有任何借阅记录！", "系统提示");
                    }
                }
                catch(Exception ex)
                {
                    throw (ex);
                }
            }
            else
            {
                if (State)
                {
                    if (logic.ReturnBook(bookid))
                    {
                        MessageBox.Show("还书成功！", "系统提示");
                        State = false;//将还书按钮变成查询按钮
                    }
                }
                else
                {
                    MessageBox.Show("还书失败！", "系统提示");
                }
            }
        }
        #endregion
    }
}
